package cn.edu.zhku.handler;

import cn.edu.zhku.constant.ResponseCode;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *  全局异常处理器
 */
@Configuration
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> map = new HashMap<>();
        if (e instanceof UnauthenticatedException
                || e instanceof UnknownAccountException
                || e instanceof IncorrectCredentialsException) {  // 未通过验证
            map.put("code", ResponseCode.unauthenticated);
            map.put("msg", e.getMessage()!=null?e.getMessage():"用户名或密码错误，请重新登录");
        } else if (e instanceof UnauthorizedException) {  // 无相关权限
            map.put("code", ResponseCode.unauthorized);
            map.put("msg", "用户无权访问");
        } else if (e instanceof ExpiredCredentialsException) {  // token失效
            map.put("code", ResponseCode.unauthenticated);
            map.put("msg", e.getMessage());
        } else {
            System.out.println(e.getMessage());
            map.put("code", ResponseCode.error);
            map.put("msg", "未知错误，请联系管理员：292832514@qq.com");
        }
        view.setAttributesMap(map);
        mv.setView(view);
        return mv;
    }

}
